"""
订单管理API
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime

from app.models.order import Order, OrderItem, OrderStatus
from app.models.product import Product, ProductVariant
from app.models.user import User
from app.schemas.order import OrderSchema, OrderItemSchema
from app.extensions import db
from app.utils.auth import admin_required

order_bp = Blueprint('order', __name__)

@order_bp.route('/', methods=['GET'])
@jwt_required()
def get_orders():
    """获取所有订单"""
    # 这里需要实现订单查询逻辑
    return jsonify({"message": "订单API - 获取所有订单"}), 200

@order_bp.route('/<int:order_id>', methods=['GET'])
@jwt_required()
def get_order(order_id):
    """获取订单详情"""
    current_user_id = get_jwt_identity()
    current_user = User.query.get(current_user_id)
    
    order = Order.query.get(order_id)
    
    if not order:
        return jsonify({"msg": "订单不存在"}), 404
    
    # 非管理员只能查看自己的订单
    if not current_user.is_admin and order.user_id != current_user_id:
        return jsonify({"msg": "无权限查看此订单"}), 403
    
    return jsonify(OrderSchema().dump(order)), 200

@order_bp.route('', methods=['POST'])
@jwt_required()
def create_order():
    """创建新订单"""
    current_user_id = get_jwt_identity()
    data = request.get_json()
    
    if not data.get('items') or len(data.get('items')) == 0:
        return jsonify({"msg": "订单商品不能为空"}), 400
    
    try:
        # 创建订单
        order = Order(
            user_id=current_user_id,
            status=OrderStatus.PENDING.value,
            shipping_address=data.get('shipping_address'),
            shipping_method=data.get('shipping_method'),
            payment_method=data.get('payment_method'),
            notes=data.get('notes')
        )
        
        # 生成订单号
        now = datetime.now()
        order.order_number = f"ORD-{now.strftime('%Y%m%d%H%M%S')}-{current_user_id}"
        
        db.session.add(order)
        db.session.flush()  # 获取订单ID
        
        total_amount = 0
        
        # 添加订单商品
        for item_data in data.get('items'):
            product_id = item_data.get('product_id')
            variant_id = item_data.get('variant_id')
            quantity = item_data.get('quantity', 1)
            
            if variant_id:
                variant = ProductVariant.query.get(variant_id)
                if not variant:
                    db.session.rollback()
                    return jsonify({"msg": f"商品变体ID {variant_id} 不存在"}), 400
                
                price = variant.price
                product = variant.product
            else:
                product = Product.query.get(product_id)
                if not product:
                    db.session.rollback()
                    return jsonify({"msg": f"商品ID {product_id} 不存在"}), 400
                
                price = product.price
            
            # 检查库存
            if variant_id and variant.stock < quantity:
                db.session.rollback()
                return jsonify({"msg": f"商品 '{product.name}' 变体库存不足"}), 400
            elif not variant_id and product.stock < quantity:
                db.session.rollback()
                return jsonify({"msg": f"商品 '{product.name}' 库存不足"}), 400
            
            # 创建订单项
            order_item = OrderItem(
                order_id=order.id,
                product_id=product_id,
                variant_id=variant_id,
                quantity=quantity,
                price=price,
                subtotal=price * quantity
            )
            
            db.session.add(order_item)
            
            # 更新库存
            if variant_id:
                variant.stock -= quantity
            else:
                product.stock -= quantity
            
            # 计算总金额
            total_amount += price * quantity
        
        # 更新订单总金额
        order.total_amount = total_amount
        
        db.session.commit()
        
        return jsonify({
            "msg": "订单创建成功",
            "order": OrderSchema().dump(order)
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"创建订单失败: {str(e)}"}), 500

@order_bp.route('/<int:order_id>/status', methods=['PUT'])
@jwt_required()
@admin_required
def update_order_status(order_id):
    """更新订单状态"""
    order = Order.query.get(order_id)
    
    if not order:
        return jsonify({"msg": "订单不存在"}), 404
    
    data = request.get_json()
    new_status = data.get('status')
    
    if not new_status:
        return jsonify({"msg": "请提供新的订单状态"}), 400
    
    try:
        # 验证状态值是否有效
        if new_status not in [status.value for status in OrderStatus]:
            return jsonify({"msg": "无效的订单状态"}), 400
        
        order.status = new_status
        db.session.commit()
        
        return jsonify({
            "msg": "订单状态更新成功",
            "order": OrderSchema().dump(order)
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"更新订单状态失败: {str(e)}"}), 500

@order_bp.route('/<int:order_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_order(order_id):
    """删除订单"""
    order = Order.query.get(order_id)
    
    if not order:
        return jsonify({"msg": "订单不存在"}), 404
    
    try:
        # 恢复库存
        for item in order.items:
            if item.variant_id:
                variant = ProductVariant.query.get(item.variant_id)
                if variant:
                    variant.stock += item.quantity
            else:
                product = Product.query.get(item.product_id)
                if product:
                    product.stock += item.quantity
        
        db.session.delete(order)
        db.session.commit()
        
        return jsonify({"msg": "订单删除成功"}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"删除订单失败: {str(e)}"}), 500

@order_bp.route('/batch-delete', methods=['POST'])
@jwt_required()
@admin_required
def batch_delete_orders():
    """批量删除订单"""
    data = request.get_json()
    order_ids = data.get('order_ids')
    
    if not order_ids or not isinstance(order_ids, list):
        return jsonify({"msg": "请提供有效的订单ID列表"}), 400
    
    try:
        # 获取所有要删除的订单
        orders = Order.query.filter(Order.id.in_(order_ids)).all()
        found_ids = [order.id for order in orders]
        
        # 检查是否所有ID都存在
        missing_ids = [id for id in order_ids if id not in found_ids]
        if missing_ids:
            return jsonify({
                "msg": "部分订单不存在",
                "missing_ids": missing_ids
            }), 400
        
        # 恢复库存并删除订单
        for order in orders:
            for item in order.items:
                if item.variant_id:
                    variant = ProductVariant.query.get(item.variant_id)
                    if variant:
                        variant.stock += item.quantity
                else:
                    product = Product.query.get(item.product_id)
                    if product:
                        product.stock += item.quantity
            
            db.session.delete(order)
        
        db.session.commit()
        
        return jsonify({
            "msg": "订单批量删除成功",
            "deleted_count": len(found_ids)
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": f"批量删除订单失败: {str(e)}"}), 500 